import csv;
import os;

class CsvExport:
    def __init__(self, offerDic):
        self.offerDic = offerDic;

    def defineHeader(self):
        return ['productImage', 'puretitle', 'productUrl', 'price', 'minOrder', 'priceMini', 'reviewScore', 'supplierName', 'supplierHomeHref', 'provideProducts'];

    def dataProcess(self):
        data = [];
        for dic in self.offerDic:
            row = {};
            row['productImage'] = dic['image']['productImage'];
            information = dic['information'];
            row['puretitle'] = information['puretitle'];
            row['productUrl'] = information['productUrl'];
            reviews = dic['reviews'];

            if 'reviewScore' in reviews.keys():
                row['reviewScore'] = reviews['reviewScore'];

            tradePrice = dic['tradePrice'];
            row['price'] = tradePrice['price'];
            row['minOrder'] = tradePrice['minOrder'];
            row['priceMini'] = tradePrice['priceMini'];

            supplier = dic['supplier'];
            row['supplierName'] = supplier['supplierName'];
            row['supplierHomeHref'] = supplier['supplierHomeHref'];
            row['provideProducts'] = supplier['provideProducts'];

            data.append(row);

        # print(data);
        return data;

    def export(self):
        data = self.dataProcess();

        # with open(os.path.join(self.path, '智联招聘_关键词_{}_城市_{}.csv'.format(self.keyword, self.city)), 'w',
        with open('../output/1.cvs', 'w',
                  newline='', encoding='utf-8-sig') as f:
            f_csv = csv.DictWriter(f, self.defineHeader())
            f_csv.writeheader()
            f_csv.writerows(data)
